package com.tangx.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tangx.article.service.ApArticleConfigService;
import com.tangx.common.constants.WmNewsMessageConstants;
import com.tangx.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * APP文章上下架的KAFKA监听器
 */
@Component
@Slf4j
public class ArticleDownOrUpListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;


    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void pollMessage(ConsumerRecord<String,String> consumerRecord){
        Optional<ConsumerRecord<String, String>> optional = Optional.ofNullable(consumerRecord);
        optional.ifPresent(x-> {
            log.info("[文章上下架MQ监听器]开始执行");
            Map newsMap = JSON.parseObject(x.value(), Map.class);
            Long articleId = Long.valueOf(newsMap.get("articleId")+""); //App文章ID
            Integer enable = Integer.valueOf(newsMap.get("enable") +""); //自媒体文章的上下架状态
            boolean isDown = true;//默认下架
            if(enable==1){
                isDown = false;//上架
            }

            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .eq(ApArticleConfig::getArticleId, articleId)  //更新条件
                    .set(ApArticleConfig::getIsDown,isDown ) //更新的字段和值
            );
            log.info("[文章上下架MQ监听器]执行结束");
        });
    }
}
